<template>
  <div class="moment-detail">
    <!-- 动态内容 -->
    <div class="content-section">
      <div class="user-info" @click="goToUserProfile(detail.userId)">
        <a-avatar :src="detail.avatar">
          {{ !detail.avatar ? detail.username.charAt(0).toUpperCase() : '' }}
        </a-avatar>
        <div class="user-meta">
          <div class="username">{{ detail.username }}</div>
          <div class="publish-time">{{ detail.createTime }}</div>
        </div>
      </div>
      
      <div class="markdown-content" v-html="renderedContent"></div>
      
      <div v-if="detail.imageUrl" class="image-section">
        <img :src="detail.imageUrl" @click="previewImage = detail.imageUrl" />
      </div>
      
      <div class="interaction-stats">
        <span class="stat-item">
          <a-icon type="eye" />
          {{ detail.viewCount }} 浏览
        </span>
        <span class="stat-item">
          <a-icon type="message" />
          {{ detail.commentCount }} 评论
        </span>
        <span class="stat-item" @click="handleLike">
          <a-icon :type="detail.liked ? 'heart' : 'heart-o'" 
                 :class="{ 'liked': detail.liked }"
                 :spin="liking" />
          {{ detail.likedCount }} 点赞
        </span>
        <SharePopover
          class="stat-item"
          :title="detail.content.slice(0, 50) + '...'"
          :link="getShareLink()"
        />
      </div>
    </div>

    <!-- 评论区 -->
    <div id="comments" class="comments-section">
      <div class="comments-header">
        <h3>评论列表</h3>
      </div>
      
      <!-- 评论输入框 -->
      <div class="comment-input">
        <a-textarea
          v-model="commentContent"
          placeholder="输入评论内容，支持 Markdown 语法"
          :rows="3"
          :maxLength="500"
        />
        <div class="input-footer">
          <span class="word-count">{{ commentContent.length }}/500</span>
          <a-button type="primary" :loading="submitting" @click="submitComment">发布评论</a-button>
        </div>
      </div>

      <!-- 评论列表 -->
      <a-spin :spinning="loading">
        <div class="comments-list">
          <div v-for="comment in comments" :key="comment.id" class="comment-item">
            <comment-tree
              :comment="comment"
              @reply="handleReplyComment"
            />
          </div>
        </div>
      </a-spin>
    </div>

    <!-- 回复弹窗 -->
    <a-modal
      v-model="replyVisible"
      title="回复评论"
      @ok="submitReply"
      :confirmLoading="submitting"
      @cancel="handleCancelReply"
    >
      <a-textarea
        v-model="replyContent"
        placeholder="输入回复内容，支持 Markdown 语法"
        :rows="4"
        :maxLength="500"
        :autoSize="{ minRows: 4, maxRows: 8 }"
      />
    </a-modal>

    <!-- 图片预览 -->
    <a-modal v-model="previewVisible" :footer="null" @cancel="previewImage = ''">
      <img alt="预览图片" style="width: 100%" :src="previewImage" />
    </a-modal>

    <!-- 回到顶部按钮 -->
    <div class="back-to-top" v-show="showBackTop" @click="scrollToTop">
      <a-icon type="up" />
    </div>
  </div>
</template>

<script>
import { marked } from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/atom-one-dark.css'
import DOMPurify from 'dompurify'
import request from '@/utils/request'
import CommentTree from '@/components/CommentTree.vue'
import SharePopover from '@/components/SharePopover.vue'

export default {
  name: 'MomentDetail',
  components: {
    CommentTree,
    SharePopover
  },
  data() {
    return {
      detail: {},
      comments: [],
      loading: false,
      page: 1,
      pageSize: 10,
      commentContent: '',
      replyContent: '',
      replyVisible: false,
      submitting: false,
      currentReplyTo: null,
      previewImage: '',
      previewVisible: false,
      liking: false,
      userId: localStorage.getItem('loginId') || '',
      showBackTop: false,
    }
  },
  computed: {
    renderedContent() {
      if (!this.detail?.content) return ''
      
      // 配置marked
      const renderer = {
        code(code, language) {
          const highlighted = hljs.highlightAuto(code).value
          return `
            <div class="code-block-wrapper">
              <div class="code-block-header" style="position: absolute; top: 8px; left: 0; right: 0; z-index: 1; background: transparent; display: flex; justify-content: space-between; padding: 0 16px;">
                <div class="code-block-left">
                  <span class="code-lang" style="color: #abb2bf;">${language || 'text'}</span>
                  <span class="code-block-tip" style="color: #7f8c98;">按 ← → 键可移动视角</span>
                </div>
                <div class="copy-wrapper">
                  <button class="copy-btn" style="background: transparent; border: 1px solid #4b5263; color: #abb2bf;" data-code="${encodeURIComponent(code)}">
                    <i class="anticon anticon-copy"></i>
                  </button>
                </div>
              </div>
              <pre style="position: relative; padding-top: 40px;"><code class="hljs ${language}">${highlighted}</code></pre>
            </div>`
        }
      }
      
      marked.use({ renderer })
      
      return DOMPurify.sanitize(marked(this.detail.content))
    }
  },
  async created() {
    await this.fetchDetail()
    await this.fetchComments()
  },
  mounted() {
    this.fetchDetail()
    // 添加复制按钮的点击事件监听
    document.addEventListener('click', this.handleCopyClick)
    window.addEventListener('scroll', this.handleScroll)
  },
  beforeDestroy() {
    // 移除事件监听
    document.removeEventListener('click', this.handleCopyClick)
    window.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    async fetchDetail() {
      try {
        const res = await request.post('/life/moment/queryById', {
          id: this.$route.params.id
        })
        if (res.code === 200) {
          this.detail = res.content
        }
      } catch (error) {
        console.error('获取动态详情失败:', error)
        this.$message.error('获取动态详情失败')
      }
    },
    async handleLike() {
      if (!this.userId) {
        this.$message.warning('请先登录')
        this.$router.push('/login')
        return
      }
      
      this.liking = true
      try {
        const res = await request.post('/life/moment/liked/add', {
          fromId: this.userId,
          toMomentId: this.$route.params.id
        })
        
        if (res.code === 200) {
          this.detail.liked = !this.detail.liked
          this.detail.likedCount = this.detail.liked ? this.detail.likedCount + 1 : this.detail.likedCount - 1
          this.$message.success(this.detail.liked ? '点赞成功' : '取消点赞成功')
        }
      } catch (error) {
        console.error('点赞失败:', error)
        this.$message.error('点赞失败')
      } finally {
        this.liking = false
      }
    },
    async fetchComments() {
      this.loading = true
      try {
        const res = await request.post('/life/moment/comment/list', {
          momentId: this.$route.params.id,
          parentId: "0",
          page: this.page,
          pageSize: this.pageSize
        })
        
        if (res.code === 200) {
          this.comments = res.content.list || []
          this.detail = {
            ...this.detail,
            commentCount: res.content.total || 0
          }
          
          // 在评论数据加载完成后处理滚动
          this.$nextTick(() => {
            const anchor = this.$route.query.anchor
            if (anchor === 'comment') {
              const commentsElement = document.getElementById('comments')
              if (commentsElement) {
                commentsElement.scrollIntoView({ behavior: 'smooth' })
              }
            }
          })
        }
      } catch (error) {
        console.error('获取评论列表失败:', error)
        this.$message.error('获取评论列表失败')
      } finally {
        this.loading = false
      }
    },

    async submitComment() {
      if (!this.commentContent.trim()) {
        this.$message.warning('请输入评论内容')
        return
      }
      
      this.submitting = true
      try {
        const res = await request.post('/life/moment/comment/add', {
          momentId: this.$route.params.id,
          content: this.commentContent.trim(),
          parentId: 0
        })
        
        if (res.code === 200) {
          this.$message.success('评论成功')
          this.commentContent = ''
          await this.fetchComments()
        }
      } catch (error) {
        console.error('发布评论失败:', error)
        this.$message.error('发布评论失败')
      } finally {
        this.submitting = false
      }
    },

    handleReplyComment(comment) {
      this.currentReplyTo = comment
      this.replyVisible = true
    },

    handleCancelReply() {
      this.replyContent = ''
      this.currentReplyTo = null
    },

    async submitReply() {
      if (!this.replyContent.trim()) {
        this.$message.warning('请输入回复内容')
        return
      }
      
      this.submitting = true
      try {
        const res = await request.post('/life/moment/comment/add', {
          momentId: this.$route.params.id,
          content: this.replyContent.trim(),
          parentId: this.currentReplyTo.id
        })
        
        if (res.code === 200) {
          this.$message.success('回复成功')
          this.replyContent = ''
          this.replyVisible = false
          this.currentReplyTo = null
          await this.fetchComments()
        }
      } catch (error) {
        console.error('发布回复失败:', error)
        this.$message.error('发布回复失败')
      } finally {
        this.submitting = false
      }
    },

    // 处理复制按钮点击
    handleCopyClick(e) {
      const button = e.target.closest('.copy-btn')
      if (!button) return
      
      const code = decodeURIComponent(button.dataset.code || '')
      if (!code) return
      
      // 使用 Clipboard API
      navigator.clipboard.writeText(code)
        .then(() => {
          this.$message.success('复制成功')
          // 更新按钮图标
          const icon = button.querySelector('.anticon')
          if (icon) {
            icon.className = 'anticon anticon-check'
            setTimeout(() => {
              icon.className = 'anticon anticon-copy'
            }, 2000)
          }
        })
        .catch(() => {
          this.$message.error('复制失败')
        })
    },
    
    renderContent(content) {
      return marked(content)
    },
    getShareLink() {
      return window.location.href
    },
    handleScroll() {
      // 当滚动超过300px时显示回到顶部按钮
      this.showBackTop = window.pageYOffset > 300
    },
    
    scrollToTop() {
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      })
    },
    goToUserProfile(userId) {
      if (!userId) return;
      // 判断是否是当前登录用户
      const currentUserId = localStorage.getItem('loginId');
      if (userId === currentUserId) {
        this.$router.push('/profile');  // 自己的主页不带id
      } else {
        this.$router.push(`/profile/${userId}`);  // 他人主页带id
      }
    },
  }
}
</script>

<style scoped>
.moment-detail {
  padding: 20px;
  max-width: 960px;
  margin: 0 auto;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

  /* 自定义滚动条样式 */
  &::-webkit-scrollbar {
    width: 6px;
    height: 6px;
    background-color: transparent;
  }

  &::-webkit-scrollbar-track {
    background-color: transparent;
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    transition: all 0.2s;

    &:hover {
      background-color: rgba(0, 0, 0, 0.2);
    }
  }
}

.content-section {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.user-meta {
  display: flex;
  flex-direction: column;
}

.username {
  font-size: 16px;
  font-weight: 500;
  color: #1a1a1a;
}

.publish-time {
  font-size: 14px;
  color: #8c8c8c;
}

.markdown-content {
  font-size: 16px;
  line-height: 1.8;
  color: #333;
  margin-bottom: 16px;
}

/* 代码块样式 */
.markdown-content :deep(pre) {
  margin: 16px 0;
  padding: 16px;
  background-color: #282c34;
  border-radius: 6px;
  overflow: auto;
}

.markdown-content :deep(pre code) {
  padding: 0;
  background: none;
  color: #abb2bf;
}

.markdown-content :deep(code) {
  font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, Courier, monospace;
  font-size: 14px;
  padding: 2px 6px;
  background: #f6f8fa;
  border-radius: 3px;
  color: #476582;
}

.markdown-content :deep(pre code.hljs) {
  padding: 0;
  color: #abb2bf;
}

.markdown-content :deep(pre code.hljs .hljs-keyword) {
  color: #c678dd;
}

.markdown-content :deep(pre code.hljs .hljs-string) {
  color: #98c379;
}

.markdown-content :deep(pre code.hljs .hljs-number) {
  color: #d19a66;
}

.markdown-content :deep(pre code.hljs .hljs-function) {
  color: #61afef;
}

.markdown-content :deep(pre code.hljs .hljs-comment) {
  color: #5c6370;
  font-style: italic;
}

.markdown-content :deep(pre code.hljs .hljs-title) {
  color: #61afef;
}

.markdown-content :deep(pre code.hljs .hljs-params) {
  color: #abb2bf;
}

.markdown-content :deep(pre code.hljs .hljs-built_in) {
  color: #e6c07b;
}

.markdown-content :deep(h1),
.markdown-content :deep(h2),
.markdown-content :deep(h3) {
  margin-top: 24px;
  margin-bottom: 16px;
  font-weight: 600;
  line-height: 1.25;
  border-bottom: 1px solid #eaecef;
  padding-bottom: 0.3em;
}

.markdown-content :deep(h1) {
  font-size: 2em;
}

.markdown-content :deep(h2) {
  font-size: 1.5em;
}

.markdown-content :deep(h3) {
  font-size: 1.25em;
}

.markdown-content :deep(p) {
  margin: 16px 0;
  line-height: 1.7;
}

.markdown-content :deep(ul),
.markdown-content :deep(ol) {
  padding-left: 2em;
  margin: 16px 0;
}

.markdown-content :deep(li) {
  margin: 8px 0;
}

.markdown-content :deep(blockquote) {
  margin: 16px 0;
  padding: 0 16px;
  color: #6a737d;
  border-left: 4px solid #dfe2e5;
}

.markdown-content :deep(img) {
  max-width: 100%;
  border-radius: 4px;
  margin: 16px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.markdown-content :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin: 16px 0;
}

.markdown-content :deep(th),
.markdown-content :deep(td) {
  border: 1px solid #dfe2e5;
  padding: 8px 12px;
}

.markdown-content :deep(th) {
  background-color: #f6f8fa;
}

.image-section {
  margin: 16px 0;
}

.image-section img {
  max-width: 100%;
  border-radius: 8px;
  cursor: pointer;
  transition: opacity 0.3s;
}

.image-section img:hover {
  opacity: 0.9;
}

.interaction-stats {
  display: flex;
  gap: 24px;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.stat-item {
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    color: #1890ff;
  }
  
  .anticon {
    margin-right: 4px;
  }
  
  .liked {
    color: #ff4d4f;
  }
}

.comments-section {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  margin-top: 24px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.comments-header {
  margin-bottom: 24px;
}

.comments-header h3 {
  font-size: 18px;
  font-weight: 500;
  color: #1a1a1a;
  margin: 0;
}

.comment-input {
  margin-bottom: 24px;
}

.input-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.word-count {
  color: #8c8c8c;
  font-size: 12px;
}

/* 代码块样式 */
.code-block-wrapper {
  margin: 1em 0;
  border-radius: 6px;
  background: #282c34;
  border: 1px solid #3e4451;
  overflow: hidden;
}

.code-block-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  background: #21252b;
  border-bottom: 1px solid #3e4451;
}

.code-block-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.code-block-lang {
  font-size: 12px;
  color: #abb2bf;
  text-transform: uppercase;
}

.code-block-tip {
  font-size: 12px;
  color: #7f8c98;
}

.copy-wrapper {
  display: flex;
  align-items: center;
}

.copy-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 4px 8px;
  font-size: 12px;
  color: #7f8c98;
  background: transparent;
  border: 1px solid #3e4451;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.copy-btn:hover {
  color: #d1d5da;
  background: rgba(255, 255, 255, 0.1);
}

.copy-btn .anticon {
  margin-right: 4px;
}

/* 代码高亮样��� */
.hljs {
  background: transparent !important;
  padding: 16px !important;
}

pre {
  margin: 0 !important;
  padding: 0 !important;
  background: transparent !important;
}

code {
  font-family: 'JetBrains Mono', Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace !important;
  font-size: 14px !important;
  line-height: 1.5 !important;
}

.tooltip-wrapper {
  position: relative;
}

.tooltip-wrapper:hover .tooltip-content {
  display: block;
}

.tooltip-content {
  display: none;
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  background: #1a1a1a;
  color: #ffffff;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  z-index: 999;
}

.back-to-top {
  position: fixed;
  right: 40px;
  bottom: 40px;
  width: 40px;
  height: 40px;
  background: #fff;
  border-radius: 50%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  z-index: 99;
}

.back-to-top:hover {
  background: #1890ff;
  transform: translateY(-2px);
}

.back-to-top:hover .anticon {
  color: #fff;
}

.back-to-top .anticon {
  font-size: 18px;
  color: #1890ff;
  transition: all 0.3s;
}

/* 评论区的滚动条样式 */
.comments-section {
  &::-webkit-scrollbar {
    width: 6px;
    height: 6px;
    background-color: transparent;
  }

  &::-webkit-scrollbar-track {
    background-color: transparent;
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    transition: all 0.2s;

    &:hover {
      background-color: rgba(0, 0, 0, 0.2);
    }
  }
}

/* 全局滚动条样式 */
:deep(html) {
  &::-webkit-scrollbar {
    width: 8px;
    height: 8px;
    background-color: transparent;
  }

  &::-webkit-scrollbar-track {
    background-color: transparent;
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgba(24, 144, 255, 0.1);
    border-radius: 4px;
    transition: all 0.2s;
    border: 2px solid transparent;
    background-clip: padding-box;

    &:hover {
      background-color: rgba(24, 144, 255, 0.2);
    }
  }
}

/* 文本域的滚动条样式 */
:deep(.ant-input) {
  &::-webkit-scrollbar {
    width: 6px;
    height: 6px;
    background-color: transparent;
  }

  &::-webkit-scrollbar-track {
    background-color: transparent;
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    transition: all 0.2s;

    &:hover {
      background-color: rgba(0, 0, 0, 0.2);
    }
  }
}
</style>